package com.chenwy.example.configuration;

import com.atomikos.jdbc.AtomikosDataSourceBean;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.DependsOn;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import java.sql.SQLException;
/**
 * Created by Administrator on 2019/5/7.
 */
@ConfigurationProperties(prefix = "slave.datasource")
@Configuration
@DependsOn("transactionManager")
@EnableJpaRepositories(basePackages = "com.chenwy.example.repository.slave", entityManagerFactoryRef = "entityManagerSlave")
@MapperScan(basePackages = "com.chenwy.example.dao.slave",sqlSessionTemplateRef = "sqlSessionTemplateSlave")
public class SlaveDBConfig extends DBConfigBase {



    @Autowired
    private DatabaseConfiguration databaseConfiguration;

    @Bean(name="slaveDataSource",initMethod = "init",destroyMethod = "close")
    public AtomikosDataSourceBean mainDataSource() throws SQLException {
        return getAtomikosDataSource(databaseConfiguration);
    }

    @Bean(name="sqlSessionFactorySlave")
    public SqlSessionFactory sqlSessionFactoryMain(@Qualifier("slaveDataSource") AtomikosDataSourceBean dataSource) throws Exception {
        SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
        sqlSessionFactoryBean.setTypeAliasesPackage(typeAliasesPackage);
        sqlSessionFactoryBean.setDataSource(dataSource);
        sqlSessionFactoryBean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath:mybatis/slave/**.xml"));
        return sqlSessionFactoryBean.getObject();
    }

    @Bean(name="sqlSessionTemplateSlave")
    public SqlSessionTemplate  sqlSessionTemplateMain(@Qualifier("sqlSessionFactorySlave") SqlSessionFactory sqlSessionFactory){
        return new SqlSessionTemplate(sqlSessionFactory);
    }


    @Bean(name="entityManagerSlave")
    public LocalContainerEntityManagerFactoryBean entityManagerFactory(@Qualifier("slaveDataSource") AtomikosDataSourceBean dataSource){
        LocalContainerEntityManagerFactoryBean entityManagerFactory = getEntityManagerFactory(dataSource);
        return entityManagerFactory;
    }
}
